using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace AvaAI批量点评系统.Services;

public class AliCloudAIService
{
    private readonly HttpClient _httpClient;
    private readonly string _apiKey;
    private readonly string _baseUrl;

    public AliCloudAIService()
    {
        _httpClient = new HttpClient();
        // 从环境变量获取API Key，如果没有则使用默认值
        _apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY") ?? "sk-ae11c7a8f0494eec84a47b2516da5a95";
        _baseUrl = "https://dashscope.aliyuncs.com/compatible-mode/v1";

        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        _httpClient.DefaultRequestHeaders.Add("User-Agent", "AvaAI-System/1.0");
    }

    // 新增：语音输入处理 - 支持实时播放
    public async Task<VoiceResponse> ProcessVoiceInputAsync(byte[] audioData, string prompt = "请听取我的语音输入，理解内容并给出回复", Action<byte[]>? onAudioChunk = null)
    {
        var base64Audio = Convert.ToBase64String(audioData);
        
        var requestBody = new
        {
            model = "qwen-omni-turbo",
            messages = new[]
            {
                new
                {
                    role = "user",
                    content = new object[]
                    {
                        new
                        {
                            type = "input_audio",
                            input_audio = new { 
                                data = $"data:audio/wav;base64,{base64Audio}",
                                format = "wav"
                            }
                        },
                        new
                        {
                            type = "text",
                            text = prompt
                        }
                    }
                }
            },
            modalities = new[] { "text", "audio" },
            audio = new
            {
                voice = "Cherry",
                format = "wav"
            },
            max_tokens = 1000,
            temperature = 0.7,
            stream = true,
            stream_options = new { include_usage = true }
        };

        var json = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", content);
            
            if (response.IsSuccessStatusCode)
            {
                // 流式处理响应，支持实时音频播放
                return await ParseVoiceStreamResponseAsync(response, onAudioChunk);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return new VoiceResponse
                {
                    TextContent = $"API调用失败: {response.StatusCode} - {errorContent}",
                    Success = false
                };
            }
        }
        catch (Exception ex)
        {
            return new VoiceResponse
            {
                TextContent = $"语音处理错误: {ex.Message}",
                Success = false
            };
        }
    }

    // 新增：纯文本输入但要求语音+文字输出 - 支持实时播放
    public async Task<VoiceResponse> GenerateVoiceResponseAsync(string textInput, string context = "", Action<byte[]>? onAudioChunk = null)
    {
        var fullPrompt = string.IsNullOrEmpty(context) ? textInput : $"{context}\n\n用户说：{textInput}";
        
        var requestBody = new
        {
            model = "qwen-omni-turbo",
            messages = new[]
            {
                new
                {
                    role = "user",
                    content = fullPrompt
                }
            },
            modalities = new[] { "text", "audio" },
            audio = new
            {
                voice = "Cherry",
                format = "wav"
            },
            max_tokens = 800,
            temperature = 0.8,
            stream = true,
            stream_options = new { include_usage = true }
        };

        var json = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", content);
            
            if (response.IsSuccessStatusCode)
            {
                // 流式处理响应，支持实时音频播放
                return await ParseVoiceStreamResponseAsync(response, onAudioChunk);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return new VoiceResponse
                {
                    TextContent = $"API调用失败: {response.StatusCode} - {errorContent}",
                    Success = false
                };
            }
        }
        catch (Exception ex)
        {
            return new VoiceResponse
            {
                TextContent = $"语音生成错误: {ex.Message}",
                Success = false
            };
        }
    }

    // 新增：正确的流式处理语音响应 - 支持实时播放版本
    private async Task<VoiceResponse> ParseVoiceStreamResponseAsync(HttpResponseMessage response, Action<byte[]>? onAudioChunk = null)
    {
        try
        {
            var textBuilder = new StringBuilder();
            var allAudioDataList = new List<string>(); // 保留完整音频用于返回
            
            Console.WriteLine("📥 开始解析流式响应...");

            using var stream = await response.Content.ReadAsStreamAsync();
            using var reader = new StreamReader(stream, Encoding.UTF8);

            string line;
            int lineCount = 0;
            int audioChunkCount = 0;
            
            while ((line = await reader.ReadLineAsync()) != null)
            {
                lineCount++;
                Console.WriteLine($"[{lineCount}] 原始行: {line}");
                
                // 处理SSE格式的流式数据
                if (line.StartsWith("data: "))
                {
                    var jsonData = line.Substring(6).Trim();
                    Console.WriteLine($"[{lineCount}] 提取数据: {jsonData}");
                    
                    // 跳过结束标记
                    if (jsonData == "[DONE]")
                    {
                        Console.WriteLine("🏁 收到结束标记 [DONE]");
                        break;
                    }

                    try
                    {
                        var chunk = JsonConvert.DeserializeObject<dynamic>(jsonData);
                        Console.WriteLine($"[{lineCount}] 解析JSON成功");
                        
                        // 检查是否有choices数组 - 根据官方p1.py结构
                        if (chunk?.choices != null)
                        {
                            var choicesArray = (Newtonsoft.Json.Linq.JArray)chunk.choices;
                            if (choicesArray.Count > 0)
                            {
                                var firstChoice = choicesArray[0];
                                var delta = firstChoice?["delta"];
                                
                                // 处理文本内容 - 对应官方代码的 delta.content
                                var contentToken = delta?["content"];
                                Console.WriteLine($"[{lineCount}] 检查文本内容Token: {contentToken} (类型: {contentToken?.Type})");
                                
                                if (contentToken != null && contentToken.Type != Newtonsoft.Json.Linq.JTokenType.Null)
                                {
                                    var textContent = contentToken.ToString();
                                    Console.WriteLine($"[{lineCount}] 提取的文本内容: '{textContent}' (长度: {textContent?.Length ?? 0})");
                                    
                                    if (!string.IsNullOrEmpty(textContent))
                                    {
                                        textBuilder.Append(textContent);
                                        Console.WriteLine($"✅ [文本] 收到并添加: '{textContent}'");
                                        Console.WriteLine($"📝 [累计] 当前文本总长度: {textBuilder.Length}");
                                    }
                                    else
                                    {
                                        Console.WriteLine($"⚠️ [文本] 文本内容为空或null");
                                    }
                                }
                                else
                                {
                                    Console.WriteLine($"⚠️ [文本] ContentToken为null或Null类型");
                                }
                                
                                // 处理音频内容 - 对应官方代码的 delta.audio - 实时播放
                                var audioToken = delta?["audio"];
                                if (audioToken != null && audioToken.Type != Newtonsoft.Json.Linq.JTokenType.Null)
                                {
                                    // 音频数据
                                    var audioDataToken = audioToken["data"];
                                    if (audioDataToken != null && audioDataToken.Type != Newtonsoft.Json.Linq.JTokenType.Null)
                                    {
                                        var audioData = audioDataToken.ToString();
                                        if (!string.IsNullOrEmpty(audioData))
                                        {
                                            audioChunkCount++;
                                            allAudioDataList.Add(audioData); // 保存完整音频
                                            
                                            Console.WriteLine($"🔊 [音频块 {audioChunkCount}] 收到: {audioData.Length} 字符");
                                            
                                            // 【关键】：实时播放音频块 - 模拟官方Python的做法
                                            if (onAudioChunk != null)
                                            {
                                                try
                                                {
                                                    var audioBytes = Convert.FromBase64String(audioData);
                                                    Console.WriteLine($"🎵 [实时播放] 音频块 {audioChunkCount}: {audioBytes.Length} 字节");
                                                    
                                                    // 立即播放这个音频块
                                                    onAudioChunk(audioBytes);
                                                }
                                                catch (Exception ex)
                                                {
                                                    Console.WriteLine($"❌ [音频块 {audioChunkCount}] 实时播放失败: {ex.Message}");
                                                }
                                            }
                                        }
                                    }
                                    
                                    // 音频转录（调试用）
                                    var transcriptToken = audioToken["transcript"];
                                    if (transcriptToken != null && transcriptToken.Type != Newtonsoft.Json.Linq.JTokenType.Null)
                                    {
                                        var transcript = transcriptToken.ToString();
                                        if (!string.IsNullOrEmpty(transcript))
                                        {
                                            Console.WriteLine($"📝 [音频] 音频转录: {transcript}");
                                        }
                                    }
                                }
                            }
                        }
                        else if (chunk?.usage != null)
                        {
                            // 处理usage信息（流结束时）
                            Console.WriteLine($"📊 Token使用情况: {chunk.usage}");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"❌ [{lineCount}] 解析JSON块失败: {ex.Message}");
                        Console.WriteLine($"❌ [{lineCount}] JSON内容: {jsonData}");
                        continue;
                    }
                }
                else if (!string.IsNullOrWhiteSpace(line))
                {
                    Console.WriteLine($"[{lineCount}] ⚠️ 非data行: {line}");
                }
                
                // 防止输出过多
                if (lineCount > 100)
                {
                    Console.WriteLine("⚠️ 行数超过100，停止详细日志");
                    break;
                }
            }

            // 合并完整音频数据（用于返回）
            byte[] completeAudioBytes = null;
            if (allAudioDataList.Count > 0)
            {
                var combinedAudioBase64 = string.Join("", allAudioDataList);
                Console.WriteLine($"🔊 完整音频数据: {allAudioDataList.Count}个块，总长度{combinedAudioBase64.Length}字符");
                
                if (!string.IsNullOrEmpty(combinedAudioBase64))
                {
                    try
                    {
                        completeAudioBytes = Convert.FromBase64String(combinedAudioBase64);
                        Console.WriteLine($"✅ 完整音频解码成功: {completeAudioBytes.Length} 字节");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"❌ 完整音频解码失败: {ex.Message}");
                    }
                }
            }

            var textResult = textBuilder.ToString();
            Console.WriteLine($"📝 最终文本结果: '{textResult}' (长度: {textResult.Length})");
            Console.WriteLine($"🎵 实时播放音频块数: {audioChunkCount}");
            Console.WriteLine($"🔊 完整音频大小: {(completeAudioBytes?.Length ?? 0)} 字节");
            
            return new VoiceResponse
            {
                TextContent = string.IsNullOrEmpty(textResult) ? "AI已回复，但文本内容为空。请检查控制台日志查看详细信息。" : textResult,
                AudioData = completeAudioBytes,
                Success = true,
                HasAudio = completeAudioBytes != null && completeAudioBytes.Length > 0
            };
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 解析语音流式响应异常: {ex}");
            return new VoiceResponse
            {
                TextContent = $"解析语音流式响应失败: {ex.Message}。请查看控制台日志获取详细信息。",
                Success = false
            };
        }
    }

    public async Task<string> AnalyzeImageAsync(string base64Image, string prompt = "请识别图片中的学生姓名和相关信息")
    {
        var requestBody = new
        {
            model = "qwen-omni-turbo",
            messages = new[]
            {
                new
                {
                    role = "user",
                    content = new object[]
                    {
                        new
                        {
                            type = "image_url",
                            image_url = new { url = $"data:image/png;base64,{base64Image}" }
                        },
                        new
                        {
                            type = "text",
                            text = prompt
                        }
                    }
                }
            },
            max_tokens = 1000,
            temperature = 0.7,
            stream = true  // qwen-omni-turbo 需要流式输出
        };

        var json = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", content);
            
            if (response.IsSuccessStatusCode)
            {
                var streamContent = await response.Content.ReadAsStringAsync();
                return ParseStreamResponse(streamContent);
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return $"API调用失败: {response.StatusCode} - {errorContent}";
            }
        }
        catch (Exception ex)
        {
            return $"错误: {ex.Message}";
        }
    }

    public async Task<string> GenerateCommentAsync(string studentName, string subject, string grade, string difficulty, bool useStream = false)
    {
        var prompt = $@"请为学生{studentName}生成一份{subject}学科的{grade}年级{difficulty}难度的期末学习评语。
要求：
1. 积极正面，具有建设性和鼓励性
2. 符合{grade}学生的理解水平
3. 体现{difficulty}难度的学习特点
4. 字数150字，内容完整，逻辑清晰
5. 不要包含任何占位符如[您的名字]、[学校名称]、[班级]等
6. 语言自然流畅，针对具体学生和课程
7. 以老师的口吻直接评价学生
8. 评语必须逻辑完整，不能出现省略号或内容截断，不能出现AI生成，请您调整等内容
9. 请直接生成评语内容，不要添加任何解释或说明。
10.不要出现 --- 以上是根据您的要求生成的一份期末学习评语示例。如果您需要进一步修改或者有其他特殊需求，请随时告知。等相关的描述";

        // 根据是否使用流式输出选择合适的模型
        var modelName = useStream ? "qwen-omni-turbo" : "qwen-turbo";

        var requestBody = new
        {
            model = modelName,
            messages = new[]
            {
                new
                {
                    role = "user",
                    content = prompt
                }
            },
            max_tokens = 400,
            temperature = 0.7,
            stream = useStream
        };

        var json = JsonConvert.SerializeObject(requestBody);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync($"{_baseUrl}/chat/completions", content);

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();

                if (useStream)
                {
                    return ParseStreamResponse(responseContent);
                }
                else
                {
                    // 非流式处理，直接解析JSON响应
                    return ParseNonStreamResponse(responseContent);
                }
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                return $"API调用失败: {response.StatusCode} - {errorContent}";
            }
        }
        catch (Exception ex)
        {
            return $"错误: {ex.Message}";
        }
    }

    private string ParseStreamResponse(string streamContent)
    {
        try
        {
            var lines = streamContent.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            var contentBuilder = new StringBuilder();

            foreach (var line in lines)
            {
                if (line.StartsWith("data: "))
                {
                    var jsonData = line.Substring(6); // 移除 "data: " 前缀
                    
                    // 跳过结束标记
                    if (jsonData.Trim() == "[DONE]")
                        continue;

                    try
                    {
                        var chunk = JsonConvert.DeserializeObject<dynamic>(jsonData);
                        var delta = chunk?.choices?[0]?.delta;
                        var content = delta?.content?.ToString();
                        
                        if (!string.IsNullOrEmpty(content))
                        {
                            contentBuilder.Append(content);
                        }
                    }
                    catch
                    {
                        // 忽略无法解析的数据块
                        continue;
                    }
                }
            }

            var result = contentBuilder.ToString();
            return string.IsNullOrEmpty(result) ? "无法解析流式响应" : result;
        }
        catch (Exception ex)
        {
            return $"解析流式响应失败: {ex.Message}";
        }
    }

    private string ParseNonStreamResponse(string responseContent)
    {
        try
        {
            dynamic response = JsonConvert.DeserializeObject(responseContent);
            var content = response?.choices?[0]?.message?.content?.ToString();
            return content ?? "评语生成失败";
        }
        catch (Exception ex)
        {
            return $"解析响应失败: {ex.Message}";
        }
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

// 新增：语音响应数据类
public class VoiceResponse
{
    public string TextContent { get; set; } = string.Empty;
    public byte[]? AudioData { get; set; }
    public bool Success { get; set; }
    public bool HasAudio { get; set; }
    public string Error { get; set; } = string.Empty;
} 